package com.yxx.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxx.mapper.ChineseWesternMedicineMapper;
import com.yxx.mapper.SetMedicineMapper;
import com.yxx.mapper.SetMedicine_MedicineMapper;
import com.yxx.medicinecommon.constant.MessageConstant;
import com.yxx.medicinecommon.constant.StatusConstant;
import com.yxx.medicinecommon.context.BaseContext;
import com.yxx.medicinecommon.exception.DeletionNotAllowedException;
import com.yxx.medicinecommon.exception.SetmedicineEnableFailedException;
import com.yxx.medicinecommon.result.PageResult;
import com.yxx.medicinecommon.result.ResponseResult;
import com.yxx.medicinepojo.dto.SetMedicinePageQueryDTO;
import com.yxx.medicinepojo.dto.SetmedicineDTO;
import com.yxx.medicinepojo.entity.ChineseWesternMedicine;
import com.yxx.medicinepojo.entity.SetMedicine;
import com.yxx.medicinepojo.entity.Setmedicine_Medicine;
import com.yxx.medicinepojo.vo.ChineseWesternMedicineDetailListVO;
import com.yxx.medicinepojo.vo.SetmedicineVO;
import com.yxx.service.MedicineCategoryService;
import com.yxx.service.SetMedicineService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * @author yuxiangxun
 * @date 2024/9/13
 * @apiNote
 */
@Service
@Slf4j
public class SetMedicineServiceImpl implements SetMedicineService {

    @Autowired
    private SetMedicineMapper setMedicineMapper;

    @Autowired
    private SetMedicine_MedicineMapper setMedicine_medicineMapper;

    @Autowired
    private ChineseWesternMedicineMapper chineseWesternMedicineMapper;

    /**
     * 组合药分页查询
     * @param setMedicinePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(SetMedicinePageQueryDTO setMedicinePageQueryDTO) {
        PageHelper.startPage(setMedicinePageQueryDTO.getPage(),setMedicinePageQueryDTO.getPageSize());
        Page<SetmedicineVO> page = setMedicineMapper.pageQuery(setMedicinePageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增组合药
     * @param setmedicineDTO
     */
    @Override
    public void saveSetdicineWithMedicine(SetmedicineDTO setmedicineDTO) {
        //新增Setmedicine对象
        SetMedicine setMedicine = new SetMedicine();

        //对象拷贝
        BeanUtils.copyProperties(setmedicineDTO,setMedicine);

        //插入组合药数据
        setMedicineMapper.insertSetMedicine(setMedicine);

        //获取insert语句中生成的主键值，终于方便插入setmedicine_medicine表
        Long setmedicine_id = setMedicine.getId();
        log.info("setmedicine_id:{}",setmedicine_id);


        //获取添加药品的列表集合
        List<Setmedicine_Medicine> medicinesList = setmedicineDTO.getSetmedicineMedicines();

        log.info("medicinesList_1:{}",medicinesList);

        if(medicinesList != null && medicinesList.size() > 0){
            //添加组合药有添加药品到组合药的记录，需要一一获取到这些药品的id到这些药品的setmealMedicines集合
            medicinesList.forEach(medicine->{
                medicine.setSetmedicineId(setmedicine_id);
                //根据传递过来的药品名称来获取药品id
                Long medicineId = chineseWesternMedicineMapper.getIdByChineseWesternMedicineName(medicine.getName());
                medicine.setMedicineId(medicineId);
            });
            
        }

        log.info("medicinesList_2:{}",medicinesList.toString());

        //向组合药药品表汇总插入n条数据
        setMedicine_medicineMapper.insertBatch(medicinesList);
    }

    /**
     * 回显数据，根据组合药id查询组合药信息
     * @param id
     * @return
     */
    @Override
    public SetmedicineVO getById_Setmedicine(Long id) {
        //根据id组合药数据
        SetMedicine setmedicine = setMedicineMapper.getBySetmedicineId(id);

        //根据组合药id
         List<Setmedicine_Medicine> setmedicine_medicines = setMedicine_medicineMapper.getBySetmedicineMedicineId(id);
         log.info("setmedicine_medicines_1:{}",setmedicine_medicines.toString());

        //查询到的组合药及药品数据封装到VO
        SetmedicineVO setmedicineVO = new SetmedicineVO();

        //对象拷贝
        BeanUtils.copyProperties(setmedicine,setmedicineVO);

        //将查询到的药品数据复制给setmedicineVO对象中的setmedicineMedicines属性
        setmedicineVO.setSetmedicineMedicines(setmedicine_medicines);
        log.info("setmedicineVO:{}", setmedicineVO);

        //遍历组合药集合，通过每一条setmedicineId获取到组合药分类，组合药表和分类表联立获取到分类id
        if(setmedicine_medicines != null && setmedicine_medicines.size() > 0) {
            setmedicine_medicines.forEach(medicine -> {
                Long typeId = setMedicine_medicineMapper.getTypeByMedicineId(medicine.getSetmedicineId());
                setmedicineVO.setCategoryId(typeId);
            });
        }
        return setmedicineVO;
    }

    /**
     * 修改组合药
     * @param setmedicineDTO
     */
    @Override
    public void update_SetMedicine_Medicine(SetmedicineDTO setmedicineDTO) {
        //创建SetMedicine对象
        SetMedicine setMedicine = new SetMedicine();
        //SetMedicine setMedicine1 = SetMedicine.builder().build();

        //对象拷贝
        BeanUtils.copyProperties(setmedicineDTO,setMedicine);

        //更新操作 组合药表
        setMedicineMapper.updateSetMedicine(setMedicine);

        //获取组合药id
        Long setmedicineId = setmedicineDTO.getId();

        log.info("setmedicineDTO.getSetmedicineMedicines:{}",setmedicineDTO.getSetmedicineMedicines());

        //修改组合药品表，先删除原先的记录（集合），在执行添加的操作（修改过程）
        setMedicineMapper.deleteBySetmedicineId(setmedicineId);
        List<Setmedicine_Medicine> setmedicineMedicines = setmedicineDTO.getSetmedicineMedicines();
        setmedicineMedicines.forEach(setmedicineMedicine -> {
            setmedicineMedicine.setSetmedicineId(setmedicineId);
            //根据每一条的中西药名称获取每一条的中医药id
            Long medicineId = chineseWesternMedicineMapper.getIdByChineseWesternMedicineName(setmedicineMedicine.getName());
            setmedicineMedicine.setMedicineId(medicineId);
        });

        log.info("setmedicineMedicines:{}",setmedicineMedicines);

        //批量插入组合药及药品信息
        setMedicine_medicineMapper.insertBatch(setmedicineMedicines);
    }

    /**
     * 组合药上架下架
     * @param status
     * @param id
     */
    @Override
    public void SetMedicine_Start_Disable(Integer status, Long id) {
        //组合药内包含为上架的药品，无法上架 -》 组合药上架时，判断组合药内是否有下架的药品，有下架的药品，提示“组合药内包含为上架的药品，组合药无法上架”
        if(StatusConstant.ENABLE.equals(status)){
            //通过组合药id查询药品信息（集合） 组合药药品表+中西药表
            List<ChineseWesternMedicine> chineseWesternMedicinesList = chineseWesternMedicineMapper.getChineseWesternMedicineStatusList(id);
            if(chineseWesternMedicinesList != null && chineseWesternMedicinesList.size() > 0){
                chineseWesternMedicinesList.forEach(chineseWesternMedicine -> {
                    if(StatusConstant.DISABLE.equals(chineseWesternMedicine.getStatus())){
                        throw new SetmedicineEnableFailedException(MessageConstant.SETMEDICINE_MEDICINE_ENABLE_FAILED);
                    }
                });
            }
        }

        //将修改信息传入setmedicine对象
        SetMedicine setMedicine = SetMedicine.builder().status(status).id(id).build();

        //修改操作
        setMedicineMapper.updateSetMedicine(setMedicine);

    }

    /**
     * 批量删除组合药
     * @param ids
     */
    @Override
    @Transactional
    public void deleteSetMedicineBatch(List<Long> ids) {
        //上架中的组合药不能删除
        for(Long id : ids){
            SetMedicine Setmedicine = setMedicineMapper.getBySetmedicineId(id);
            if(StatusConstant.ENABLE.equals(Setmedicine.getStatus())){
                throw new DeletionNotAllowedException(MessageConstant.SETMEDICINE_MEDICINE_ON_SALE);
            }
        }

        //批量删除组合药中的数据
        setMedicineMapper.deleteByIds(ids);
        //批量删除组合药药品表中的数据
        setMedicine_medicineMapper.deleteBySetMedicine(ids);
    }

    /**
     * 条件查询组合药信息
     * @param setMedicine
     * @return
     */
    @Override
    public List<SetMedicine> list(SetMedicine setMedicine) {
        List<SetMedicine> setMedicineList = setMedicineMapper.list(setMedicine);
        return setMedicineList;
    }

    /**
     * 根据组合药id查询中西药列表信息
     * @param id
     * @return
     */
    @Override
    public List<ChineseWesternMedicineDetailListVO> chineseWesternMedicineDetailListById(Long id) {
        List<ChineseWesternMedicineDetailListVO> chineseWesternMedicineDetailListVOList = chineseWesternMedicineMapper.chineseWesternMedicineDetailListById(id);
        return chineseWesternMedicineDetailListVOList;
    }


}
